package main

import (
	"fmt"
	"log"
	"os"
	"os/signal"
	"syscall"

	"github.com/nsqio/go-nsq"
)

type myMessageHandler struct{}

func (h *myMessageHandler) HandleMessage(m *nsq.Message) error {
	if len(m.Body) == 0 {
		return nil
	}

	err := processMessage(m.Body)
	return err
}

func processMessage(m []byte) error {
	fmt.Printf("%s\n", m)
	return nil
}

// 消费消息时，访问地址有问题
const LookupAddr = "172.21.0.2:4161"

func main() {
	config := nsq.NewConfig()
	consumer, err := nsq.NewConsumer("order", "message01", config)
	if err != nil {
		log.Fatal(err)
	}
	consumer.AddHandler(&myMessageHandler{})
	// 直连 nsq
	// err = consumer.ConnectToNSQD("<NsqdAddr>:4150")
	// 链接 nsqLookup
	err = consumer.ConnectToNSQLookupd(LookupAddr)
	if err != nil {
		log.Fatal(err)
	}

	sigChan := make(chan os.Signal, 1)
	signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
	<-sigChan

	consumer.Stop()
}
